from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.template import defaultfilters
from django.contrib.contenttypes import generic
from threadedcomments.models import ThreadedComment

class ThreadedForumManager(models.Manager):
    pass

class Category(models.Model):

    name = models.CharField(max_length=128)
    description = models.TextField()
    slug = models.SlugField(unique=True)
    
    #admin data
    is_closed = models.BooleanField(default=False)
    is_hidden = models.BooleanField(default=False)
    is_private = models.BooleanField(default=False)
    
    #calculated data
    date_added = models.DateTimeField()

    def save(self):
        if not self.pk:
            self.date_added = datetime.now()
        self.slug = defaultfilters.slugify(self.name)
        super(Category,self).save()
    
    def __unicode__(self):
        return self.name
    
    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
    
    class Admin:
        pass

class Thread(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=128)
    body = models.TextField()
    category = models.ForeignKey(Category)
    
    #admin data
    is_sticky = models.BooleanField(default=False)
    is_closed = models.BooleanField(default=False)
    is_hidden = models.BooleanField(default=False)
    is_private = models.BooleanField(default=False)
    
    #denormalised data
    views = models.IntegerField(default=0, editable=False)
    replies = models.IntegerField(default=0, editable=False)
    
    #calculated data
    date_modified = models.DateTimeField(default=datetime.now, editable=False)
    date_created = models.DateTimeField(default=datetime.now, editable=False)
    
    objects = ThreadedForumManager()
    replies = generic.GenericRelation(ThreadedComment)
    
    def save(self):
        if not self.pk:
            date_created = datetime.now
        date_modified = datetime.now
        super(Thread,self).save()

    def __unicode__(self):
        return self.title
    
    class Admin:
        pass
